#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <fcntl.h>    /* For O_* constants */
#include <sys/stat.h> /* For mode constants */
#include <semaphore.h>

// 练习1：使用互斥锁+多线程实现整形矩阵（二维整形数组）所有元素求和问题
pthread_mutex_t mutex;
int total = 0;
#define N 5
int array[N][N] = {10, 20, 30, 40, 50,
                   11, 22, 33, 44, 55,
                   66, 77, 88, 99, 11,
                   12, 31, 12, 34, 45,
                   12, 43, 45, 66, 77};

void *sum_line(void *arg)
{

    int i = *(int *)arg;
    int sum = 0;
    for (int j = 0; j < N; j++)
    {
        sum += array[i][j];
    }
    pthread_mutex_lock(&mutex);
    total += sum;
    printf("sum_line:%d\n", sum);
    pthread_mutex_unlock(&mutex);
}

int main()
{

    int i[5] = {0, 1, 2, 3, 4};

    pthread_t tid[5];

    pthread_mutex_init(&mutex, NULL);

    pthread_create(&tid[0], NULL, sum_line, &i[0]);
    pthread_create(&tid[1], NULL, sum_line, &i[1]);
    pthread_create(&tid[2], NULL, sum_line, &i[2]);
    pthread_create(&tid[3], NULL, sum_line, &i[3]);
    pthread_create(&tid[4], NULL, sum_line, &i[4]);

    pthread_join(tid[0], NULL);
    pthread_join(tid[1], NULL);
    pthread_join(tid[2], NULL);
    pthread_join(tid[3], NULL);
    pthread_join(tid[4], NULL);

    pthread_mutex_destroy(&mutex);

    printf("total:%d\n", total);
    return 0;
}
